package SwordFingerOffer;

import java.util.ArrayList;
import java.util.List;

public class Q29_PrintMatrix {
    //顺时针打印矩阵

    //本题还是宏观调度
    //忘了咋宏观调度的了...
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix == null  || matrix.length == 0){
            return new int[]{};
        }

        int topRow = 0;
        int topCol = 0;
        int downRow = matrix.length - 1;
        int downCol = matrix[0].length - 1;
        List<Integer> ans = new ArrayList<>();

        while (topCol <= downCol && topRow <= downRow){
            process(matrix, topRow++, topCol++, downRow--, downCol--, ans);
        }

        //换回数组
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            res[i] = ans.get(i);
        }
        return res;
    }

    //左上角 右下角 坐标
    public static void process(int[][] matrix, int topRow, int topCol, int downRow, int downCol, List<Integer> ans){

        //一行的情况 一点的情况也能处理
        if (topRow == downRow){
            for (int i = topCol; i <= downCol ; i++) {
                ans.add(matrix[topRow][i]);
            }
            return;
        }
        //一列的情况
        if (topCol == downCol){
            for (int i = topRow; i <= downRow ; i++) {
                ans.add(matrix[i][topCol]);
            }
            return;
        }

        //左到右打印列
        for (int i = topCol; i < downCol ; i++) {
            ans.add(matrix[topRow][i]);
        }
        //上到下打印行
        for (int i = topRow; i < downRow; i++) {
            ans.add(matrix[i][downCol]);
        }
        //右到左打印列
        for (int i = downCol; i > topCol; i--) {
            ans.add(matrix[downRow][i]);
        }
        //下到上打印行
        for (int i = downRow; i > topRow ; i--) {
            ans.add(matrix[i][topCol]);
        }
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(spiralOrder(matrix));
    }
}
